<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:text="${title}">SSE功能测试</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #ff6b6b 0%, #feca57 100%);
            min-height: 100vh;
            color: #333;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        .header {
            text-align: center;
            margin-bottom: 30px;
            color: white;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
        }

        .nav {
            background: rgba(255,255,255,0.95);
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }

        .nav a {
            color: #ff6b6b;
            text-decoration: none;
            margin: 0 15px;
            font-weight: bold;
        }

        .nav a:hover {
            text-decoration: underline;
        }

        .test-panel {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 30px;
        }

        @media (max-width: 768px) {
            .test-panel {
                grid-template-columns: 1fr;
            }
        }

        .card {
            background: rgba(255,255,255,0.95);
            border-radius: 15px;
            padding: 20px;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }

        .card h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 1.3em;
            border-bottom: 2px solid #ff6b6b;
            padding-bottom: 8px;
        }

        .status-bar {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .connection-status {
            display: flex;
            align-items: center;
        }

        .status-indicator {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 8px;
        }

        .status-connected {
            background: #4CAF50;
        }

        .status-disconnected {
            background: #f44336;
        }

        .test-controls {
            margin-bottom: 20px;
        }

        .control-group {
            margin-bottom: 15px;
        }

        .control-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #333;
        }

        .control-group input, 
        .control-group select, 
        .control-group textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
        }

        .control-group textarea {
            height: 80px;
            resize: vertical;
        }

        .btn {
            background: #ff6b6b;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            margin-bottom: 10px;
            transition: background 0.3s;
        }

        .btn:hover {
            background: #ff5252;
        }

        .btn-secondary {
            background: #6c757d;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        .btn-success {
            background: #28a745;
        }

        .btn-success:hover {
            background: #218838;
        }

        .message-log {
            background: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            max-height: 400px;
            overflow-y: auto;
            font-family: 'Courier New', monospace;
            font-size: 13px;
        }

        .log-entry {
            margin-bottom: 8px;
            padding: 5px;
            border-left: 3px solid #ff6b6b;
            background: white;
            border-radius: 3px;
        }

        .log-time {
            color: #666;
            font-size: 11px;
        }

        .log-content {
            margin-top: 3px;
            color: #333;
        }

        .test-results {
            margin-top: 20px;
        }

        .result-item {
            background: #e9ecef;
            padding: 10px;
            margin-bottom: 10px;
            border-radius: 5px;
            border-left: 4px solid #28a745;
        }

        .result-item.error {
            border-left-color: #dc3545;
            background: #f8d7da;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1 th:text="${title}">SSE功能测试</h1>
            <p>测试 Server-Sent Events 的各种功能</p>
        </div>

        <div class="nav">
            <a href="/">首页</a>
            <a href="/monitor">监控面板</a>
            <a href="/test">功能测试</a>
        </div>

        <!-- 连接状态 -->
        <div class="status-bar">
            <div class="connection-status">
                <span class="status-indicator status-disconnected" id="statusIndicator"></span>
                <span id="connectionStatus">未连接</span>
            </div>
            <div>
                <span>客户端ID: </span>
                <span id="clientId">--</span>
            </div>
        </div>

        <div class="test-panel">
            <!-- 测试控制面板 -->
            <div class="card">
                <h3>🧪 测试控制</h3>
                
                <div class="test-controls">
                    <div class="control-group">
                        <label for="messageType">消息类型:</label>
                        <select id="messageType">
                            <option value="user-action">用户操作</option>
                            <option value="system-notification">系统通知</option>
                            <option value="heartbeat">心跳检测</option>
                            <option value="custom">自定义</option>
                        </select>
                    </div>
                    
                    <div class="control-group">
                        <label for="messageContent">消息内容:</label>
                        <textarea id="messageContent" placeholder="输入要发送的消息内容...">测试消息</textarea>
                    </div>
                    
                    <div style="margin-bottom: 20px;">
                        <button class="btn" onclick="sendTestMessage()">📤 发送消息</button>
                        <button class="btn btn-secondary" onclick="triggerHeartbeat()">💓 触发心跳</button>
                    </div>
                </div>

                <div class="test-controls">
                    <h4>连接测试</h4>
                    <button class="btn btn-success" onclick="connectSSE()">🔗 连接SSE</button>
                    <button class="btn btn-secondary" onclick="disconnectSSE()">🔌 断开连接</button>
                    <button class="btn" onclick="reconnectSSE()">🔄 重新连接</button>
                </div>

                <div class="test-controls">
                    <h4>压力测试</h4>
                    <div class="control-group">
                        <label for="stressCount">发送次数:</label>
                        <input type="number" id="stressCount" value="10" min="1" max="100">
                    </div>
                    <button class="btn" onclick="startStressTest()">⚡ 开始压力测试</button>
                    <button class="btn btn-secondary" onclick="clearLog()">🗑️ 清空日志</button>
                </div>
            </div>

            <!-- 消息日志 -->
            <div class="card">
                <h3>📋 消息日志</h3>
                <div class="message-log" id="messageLog">
                    <div class="log-entry">
                        <div class="log-time">系统就绪</div>
                        <div class="log-content">等待连接...</div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 测试结果 -->
        <div class="card">
            <h3>📊 测试结果</h3>
            <div class="test-results" id="testResults">
                <p>开始测试后，结果将显示在这里...</p>
            </div>
        </div>
    </div>

    <script>
        let eventSource = null;
        let clientId = null;
        let messageCount = 0;
        let errorCount = 0;
        let startTime = null;

        // 页面加载完成后延迟连接
        document.addEventListener('DOMContentLoaded', function() {
            setTimeout(connectSSE, 1000);
        });

        // 连接SSE
        function connectSSE() {
            if (eventSource && eventSource.readyState !== EventSource.CLOSED) {
                addLogEntry('连接已存在，先断开当前连接');
                eventSource.close();
            }

            clientId = 'test_client_' + Date.now();
            document.getElementById('clientId').textContent = clientId;
            
            addLogEntry(`🔗 正在连接SSE服务... 客户端ID: ${clientId}`);
            
            eventSource = new EventSource(`/api/sse/connect?clientId=${clientId}`);
            startTime = Date.now();

            eventSource.onopen = function(event) {
                addLogEntry('✅ SSE连接成功建立');
                updateConnectionStatus(true);
                addTestResult('连接测试', '成功', '连接建立时间: ' + (Date.now() - startTime) + 'ms');
            };

            eventSource.onmessage = function(event) {
                messageCount++;
                addLogEntry(`📨 收到消息: ${event.data}`);
                
                try {
                    const data = JSON.parse(event.data);
                    addLogEntry(`📋 解析结果: 类型=${data.type}, 消息=${data.message}`);
                } catch (e) {
                    addLogEntry(`⚠️ JSON解析失败: ${e.message}`);
                }
            };

            eventSource.onerror = function(event) {
                errorCount++;
                addLogEntry('❌ SSE连接出现错误');
                updateConnectionStatus(false);
                addTestResult('连接错误', '失败', `错误次数: ${errorCount}`);
                
                // 自动重连
                setTimeout(() => {
                    if (eventSource.readyState === EventSource.CLOSED) {
                        addLogEntry('🔄 5秒后尝试自动重连...');
                        setTimeout(connectSSE, 5000);
                    }
                }, 100);
            };

            // 监听特定事件类型
            eventSource.addEventListener('heartbeat', function(event) {
                addLogEntry(`💓 心跳: ${event.data}`);
            });

            eventSource.addEventListener('user-action', function(event) {
                addLogEntry(`👤 用户操作: ${event.data}`);
            });

            eventSource.addEventListener('system-notification', function(event) {
                addLogEntry(`🔔 系统通知: ${event.data}`);
            });
        }

        // 断开连接
        function disconnectSSE() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
                addLogEntry('🔌 手动断开SSE连接');
                updateConnectionStatus(false);
            }
        }

        // 重新连接
        function reconnectSSE() {
            addLogEntry('🔄 重新连接SSE...');
            disconnectSSE();
            setTimeout(connectSSE, 1000);
        }

        // 发送测试消息
        function sendTestMessage() {
            const type = document.getElementById('messageType').value;
            const content = document.getElementById('messageContent').value;
            
            if (!content.trim()) {
                alert('请输入消息内容');
                return;
            }

            const testData = {
                type: type,
                message: content,
                timestamp: new Date().toISOString()
            };

            addLogEntry(`📤 发送测试消息: 类型=${type}, 内容=${content}`);

            fetch('/api/test/broadcast', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(testData)
            })
            .then(response => response.json())
            .then(data => {
                addLogEntry(`✅ 消息发送成功: ${JSON.stringify(data)}`);
                addTestResult('消息发送', '成功', `类型: ${type}`);
            })
            .catch(error => {
                addLogEntry(`❌ 消息发送失败: ${error.message}`);
                addTestResult('消息发送', '失败', error.message);
            });
        }

        // 触发心跳
        function triggerHeartbeat() {
            addLogEntry('💓 触发心跳检测...');
            
            fetch('/api/test/heartbeat', {
                method: 'POST'
            })
            .then(response => response.text())
            .then(data => {
                addLogEntry(`✅ 心跳触发成功: ${data}`);
                addTestResult('心跳测试', '成功', '心跳信号已发送');
            })
            .catch(error => {
                addLogEntry(`❌ 心跳触发失败: ${error.message}`);
                addTestResult('心跳测试', '失败', error.message);
            });
        }

        // 压力测试
        function startStressTest() {
            const count = parseInt(document.getElementById('stressCount').value);
            if (count < 1 || count > 100) {
                alert('发送次数应在1-100之间');
                return;
            }

            addLogEntry(`⚡ 开始压力测试，将发送 ${count} 条消息...`);
            const startTime = Date.now();
            let successCount = 0;
            let failCount = 0;

            for (let i = 1; i <= count; i++) {
                setTimeout(() => {
                    const testData = {
                        type: 'stress-test',
                        message: `压力测试消息 ${i}/${count}`,
                        timestamp: new Date().toISOString()
                    };

                    fetch('/api/test/broadcast', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(testData)
                    })
                    .then(response => response.json())
                    .then(data => {
                        successCount++;
                        if (successCount + failCount === count) {
                            const duration = Date.now() - startTime;
                            addLogEntry(`🏁 压力测试完成: 成功${successCount}条, 失败${failCount}条, 耗时${duration}ms`);
                            addTestResult('压力测试', '完成', `${successCount}/${count} 成功, 耗时${duration}ms`);
                        }
                    })
                    .catch(error => {
                        failCount++;
                        if (successCount + failCount === count) {
                            const duration = Date.now() - startTime;
                            addLogEntry(`🏁 压力测试完成: 成功${successCount}条, 失败${failCount}条, 耗时${duration}ms`);
                            addTestResult('压力测试', '完成', `${successCount}/${count} 成功, 耗时${duration}ms`);
                        }
                    });
                }, i * 100); // 每100ms发送一条
            }
        }

        // 清空日志
        function clearLog() {
            document.getElementById('messageLog').innerHTML = '';
            addLogEntry('日志已清空');
        }

        // 更新连接状态
        function updateConnectionStatus(connected) {
            const indicator = document.getElementById('statusIndicator');
            const status = document.getElementById('connectionStatus');
            
            if (connected) {
                indicator.className = 'status-indicator status-connected';
                status.textContent = '已连接';
            } else {
                indicator.className = 'status-indicator status-disconnected';
                status.textContent = '未连接';
            }
        }

        // 添加日志条目
        function addLogEntry(message) {
            const logContainer = document.getElementById('messageLog');
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            
            const now = new Date();
            const timeStr = now.toLocaleTimeString() + '.' + now.getMilliseconds().toString().padStart(3, '0');
            
            logEntry.innerHTML = `
                <div class="log-time">${timeStr}</div>
                <div class="log-content">${message}</div>
            `;
            
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        // 添加测试结果
        function addTestResult(testName, result, details) {
            const resultsContainer = document.getElementById('testResults');
            const resultItem = document.createElement('div');
            resultItem.className = 'result-item' + (result === '失败' ? ' error' : '');
            
            const now = new Date().toLocaleTimeString();
            resultItem.innerHTML = `
                <strong>${testName}</strong> - ${result} <span style="float: right; color: #666;">${now}</span><br>
                <small>${details}</small>
            `;
            
            resultsContainer.appendChild(resultItem);
        }

        // 页面卸载时清理
        window.addEventListener('beforeunload', function() {
            if (eventSource) {
                eventSource.close();
            }
        });
    </script>
</body>
</html>